# app/monitoring/models

from django.db import models
from apps.rooms.models import Room
from apps.users.models import User
from apps.devices.models import Device


class SensorReading(models.Model):
    """
    温湿度读数表：前端实时展示数据来源。
    """
    reading_id   = models.AutoField(primary_key=True)
    room         = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="readings")
    temperature  = models.DecimalField(max_digits=5, decimal_places=2)  # -99.99~999.99
    humidity     = models.DecimalField(max_digits=5, decimal_places=2)  # 0.00~100.00
    recorded_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table  = "sensor_readings"
        ordering  = ["-recorded_at"]

    def __str__(self):
        return f"{self.room.name} @ {self.recorded_at:%F %T}"


class ActionLog(models.Model):
    """
    操作日志表：记录用户或系统对设备/系统的所有改动。
    """
    log_id       = models.AutoField(primary_key=True)
    user         = models.ForeignKey(User,   null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name="logs")
    device       = models.ForeignKey(Device, null=True, blank=True,
                                     on_delete=models.SET_NULL, related_name="logs")
    action_type  = models.CharField(max_length=50)          # 如：'修改温度'
    old_value    = models.CharField(max_length=255, null=True, blank=True)
    new_value    = models.CharField(max_length=255, null=True, blank=True)
    timestamp    = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table  = "action_logs"
        ordering  = ["-timestamp"]

    def __str__(self):
        return f"{self.action_type} @ {self.timestamp:%F %T}"